package com.example.rabbitmq.convert;

import com.example.rabbitmq.Test;
import com.example.rabbitmq.pojo.TestPojo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

public class CustomConverter<T> implements MessageConverter {


    private ObjectMapper objectMapper = new ObjectMapper();
    private Class<T> tClass;
    public CustomConverter(Class<T> tClass){
        this.tClass=tClass;
    }
    //将java对象转换为消息
    //注意：消息发送的时候，消息是什么类型，如果消息发送过来就是json字符串，那么反序列化后，该队列还是字符串，这时如果用TestPojo就会报错
    @Override
    public Message toMessage(Object object, MessageProperties messageProperties) throws MessageConversionException {
        String json = null;
        try {
            json = objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return new Message(json.getBytes(StandardCharsets.UTF_8),messageProperties);
    }

    @Override
    public Message toMessage(Object object, MessageProperties messageProperties, Type genericType) throws MessageConversionException {
        return MessageConverter.super.toMessage(object, messageProperties, genericType);
    }

    //将消息转换为java对象
    @Override
    public T fromMessage(Message message) throws MessageConversionException {

        String json = new String(message.getBody(), StandardCharsets.UTF_8);
        T testPojo = null;
        try {
            testPojo=objectMapper.readValue(json, tClass);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return testPojo;
    }
}
